<template>
  <ul>
    <li v-for="item in menu" :key="item.id" :class="{ active: item.id === selected }">
      <a @click="toggleMenu(item.id)">
        {{ item.name }}
        <span v-if="item.children.length" :class="{ expanded: item.expanded }">
          <i class="fa fa-chevron-down" v-if="!item.expanded"></i>
          <i class="fa fa-chevron-up" v-if="item.expanded"></i>
        </span>
      </a>
      <Menu
        v-if="item.children.length && item.expanded"
        :menu="item.children"
        :selected="selected"
        @select="selectItem"
      ></Menu>
    </li>
  </ul>
</template>

<script>
import Menu from "./Menu.vue";
export default {
  components: { Menu },
  props: {
    menu: {
      type: Array,
      default: () => [],
    },
    selected: {
      type: String,
      default: "",
    },
  },
  emits: ["select"],
  methods: {
    toggleMenu(id) {
      const item = this.menu.find((item) => item.id === id);
      if (item) {
        item.expanded = !item.expanded;
      }
    },
    selectItem(id) {
      this.$emit("select", id);
    },
  },
};
</script>

<style>
ul {
  padding: 0;
  margin: 0;
  list-style-type: none;
}
li {
  padding: 5px;
}
.active a {
  color: white;
  background-color: gray;
}
span {
  padding: 0 5px;
}
i {
  font-size: 12px;
}
.expanded + i.fa-chevron-down {
  display: none;
}
</style>
